const { RouterModel } = require('../../models');
const RouterService = {
  add: async data => {
    //  判断path是否存在
    const row = await RouterModel.findOne({ path: data.path, menuType: 0 });
    if (row) {
      return {
        success: false,
        msg: '该路由已存在',
        data: null,
      };
    } else {
      const result = await RouterModel.create(data);
      return {
        success: true,
        msg: '添加成功',
        data: result,
      };
    }
  },

  edit: async (_id, data) => {
    const row = await RouterModel.findOne({ path: data.path, menuType: 0 });
    console.log(row);
    if (row && row._id != _id) {
      return {
        success: false,
        msg: '该路由已存在',
        data: null,
      };
    } else {
      const result = await RouterModel.updateOne({ _id }, data);
      return {
        success: true,
        msg: '修改成功',
        // data: result,
      };
    }
  },

  list: async () => {
    const result = await RouterModel.find({}, ['meta', 'menuType', 'title', 'type', 'path', 'icon', 'auth', 'component', 'parentId']);

    if (!result) {
      return {
        success: false,
        msg: '查询失败',
        data: null,
      };
    } else {
      return {
        success: true,
        msg: '查询成功',
        data: result,
      };
    }
  },

  // 删除路由
  delete: async _id => {
    const result = await RouterModel.deleteOne({ _id });
    if (!result) {
      return {
        success: false,
        msg: '删除失败',
        data: null,
      };
    } else {
      return {
        success: true,
        msg: '删除成功',
      };
    }
  },
  // 获取详情
  findById: async _id => {
    const result = await RouterModel.findOne({ _id }, ['meta', 'menuType', 'title', 'type', 'path', 'icon', 'auth', 'component', 'parentId']);
    if (!result) {
      return {
        success: false,
        msg: '查询失败',
        data: null,
      };
    } else {
      return {
        success: true,
        msg: '查询成功',
        data: result,
      };
    }
  },
  // 获取所有的菜单节点
  getAllMenu: async () => {
    const result = await RouterModel.find({ menuType: 1, type: 0 }, ['title']);
    if (!result) {
      return {
        success: false,
        msg: '查询失败',
        data: null,
      };
    } else {
      return {
        success: true,
        msg: '查询成功',
        data: result,
      };
    }
  },
};

module.exports = RouterService;
